import React from 'react';
import { Form, Table, Button, Input, Drawer, Typography, message } from 'antd';
import FileUpload from '@/components/Custom/FileUpload';
import { Icon } from '@/pages/Recruitment/components';
import { FormLayout } from '../../components';
import AccessTable from '../AccessTable';
import AssessTag from './AssessTag';
import { requireRule } from '../../utils';
import styles from './index.less';

const map = { weekly: '周', monthly: '月', quarterly: '季' };
export default function AssessAbility({ form, data = {} }) {
    const { getFieldDecorator } = form;
    const [visible, setVisible] = React.useState(false);
    const { assessAbility = {}, opEmployeeName = '-', period } = data;
    const [projectInitialValue, setProjectInitialValue] = React.useState(null);
    const [changed, setChanged] = React.useState(false);
    const { levels = [] } = assessAbility;

    const columns = [
        {
            title: '评估人',
            dataIndex: 'assessEmployeeName',
            width: '30%',
            editable: true
        },
        {
            title: '评估表',
            dataIndex: 'projectName',
            editable: true
        },
        {
            title: '分数',
            dataIndex: 'score',
            editable: true
        },
        {
            title: '等级',
            dataIndex: 'level',
            editable: true,
            render(text) {
                return <AssessTag title={text} onlyText levels={levels} />;
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            width: 100,
            render: () => (
                <Icon
                    title="填写评估表"
                    type="listfunction_edit_icon_default"
                    onClick={() => {
                        setVisible(true);
                    }}
                />
            )
        }
    ];

    const accessResult = React.useMemo(() => {
        // 从未修改评估表
        if (!projectInitialValue && !changed) {
            return { score: '', level: '' };
        }
        const { project = [] } = form.getFieldsValue();
        const sum = project.reduce((prev, { weight = 0, score = 0 }) => prev + weight * score, 0) / 100;

        const levelItem =
            levels.find(({ min, max }) => (Number(min) < sum || Number(min) === 0) && sum <= Number(max)) || {};
        return { score: sum.toFixed(2), level: levelItem.level };
    }, [form, data, projectInitialValue]);

    const dataSource = [
        {
            key: '1',
            assessEmployeeName: opEmployeeName,
            level: accessResult.level,
            score: accessResult.score,
            projectName: assessAbility.projectName
        }
    ];

    React.useEffect(() => {
        form.setFieldsValue({ assessSummary: dataSource });
    }, [projectInitialValue]);

    // 初始值 score 不应有值
    const initialValue = React.useMemo(
        () =>
            assessAbility.project.map(item => ({
                ...item,
                score: undefined
            })),
        [assessAbility.project]
    );

    const renderResultText = text => {
        if (text === '') {
            return <Typography.Text type="secondary">自动计算</Typography.Text>;
        }
        return text;
    };

    return (
        <div className={styles.assessAbility}>
            <Drawer
                maskClosable={false}
                width={800}
                placement="right"
                closable={false}
                onClose={() => {
                    setVisible(false);
                }}
                visible={visible}
                bodyStyle={{ overflow: 'hidden', height: '100%', padding: 0 }}
            >
                <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', height: '100%' }}>
                    <div
                        style={{
                            display: 'flex',
                            flexDirection: 'column',
                            flex: 1,
                            margin: 24,
                            overflow: 'auto',
                            border: '1px solid #e8e8e8',
                            background: '#fafafa'
                        }}
                    >
                        <div
                            style={{
                                width: '100%',
                                borderBottom: '1px solid #e8e8e8',
                                padding: '10px 16px',
                                background: '#FAFAFA'
                            }}
                        >
                            <Typography.Title level={4} style={{ marginBottom: 0, textAlign: 'center' }}>
                                {assessAbility.projectName}
                            </Typography.Title>
                        </div>
                        <div
                            style={{
                                width: '100%',
                                borderBottom: '1px solid #e8e8e8',
                                display: 'flex',
                                padding: '10px 24px'
                            }}
                        >
                            <div style={{ flex: 1 }}>
                                <strong>最终得分：{renderResultText(accessResult.score)}</strong>
                            </div>
                            <div style={{ flex: 1 }}>
                                <strong>最终级别：{renderResultText(accessResult.level)}</strong>
                            </div>
                        </div>
                        <div style={{ flex: 1, overflow: 'hidden' }}>
                            {getFieldDecorator('project', { initialValue })(
                                <AccessTable
                                    footer={() => <pre>{assessAbility.projectExplain}</pre>}
                                    onChange={() => {
                                        setChanged(true);
                                    }}
                                />
                            )}
                        </div>
                    </div>

                    <div
                        style={{
                            width: '100%',
                            borderTop: '1px solid #e8e8e8',
                            padding: '10px 16px',
                            textAlign: 'right',
                            background: '#fff',
                            borderRadius: '0 0 4px 4px'
                        }}
                    >
                        <Button
                            style={{
                                marginRight: 8
                            }}
                            onClick={() => {
                                form.setFieldsValue({ project: projectInitialValue || assessAbility.project });
                                setVisible(false);
                                setChanged(false);
                            }}
                        >
                            取消
                        </Button>
                        <Button
                            type="primary"
                            onClick={() => {
                                const { project = [] } = form.getFieldsValue();
                                const hasSomeUnAssessed = project.some(item => item.score === undefined);
                                if (hasSomeUnAssessed) {
                                    message.warning('请完成全部评估项目的评分！');
                                    return;
                                }
                                setProjectInitialValue(project);
                                setVisible(false);
                            }}
                        >
                            确定
                        </Button>
                    </div>
                </div>
            </Drawer>

            <div style={{ width: 900 }}>
                <FormLayout type="full">
                    <Form.Item label="我的评估">
                        <AssessTag title={accessResult.level} levels={levels} />
                    </Form.Item>
                </FormLayout>
                <FormLayout type="full">
                    <Form.Item label={`${map[period]}评估表`} required>
                        {getFieldDecorator('assessSummary', {
                            rules: [
                                {
                                    validator(rule, value = [], callback) {
                                        const result = value[0] || {};
                                        if (result.level === '' || result.score === '') {
                                            callback('请完成评估表');
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })(
                            <Table rowKey="key" columns={columns} dataSource={dataSource} pagination={false} bordered />
                        )}
                    </Form.Item>
                </FormLayout>
                <FormLayout type="full">
                    <Form.Item label="评估意见">
                        {getFieldDecorator('opinion', { rules: requireRule('请输入评估意见') })(
                            <Input.TextArea rows={7} placeholder="请输入" maxLength={500} />
                        )}
                    </Form.Item>
                </FormLayout>
                <FormLayout type="full">
                    <Form.Item label="注意事项" extra="评估完成后将提醒新员工查看">
                        {getFieldDecorator('announcements', { rules: requireRule('请输入注意事项') })(
                            <Input.TextArea rows={7} placeholder="请输入" maxLength={500} />
                        )}
                    </Form.Item>
                </FormLayout>
                <FormLayout type="full" style={{ marginTop: 16 }}>
                    <Form.Item
                        label="附件"
                        help="支持 pdf、doc(x)、xls(x)、jp(e)g、png、rar 等格式的附件，单个文件大小为10MB以内"
                    >
                        {getFieldDecorator('resourceRelation')(
                            <FileUpload
                                categoryCode="probationAssessFile"
                                checkFileSize={10}
                                maxFileCount={1}
                                checkFileType="pdf、doc、docx、jpg、jpeg、png、rar、xls、xlsx"
                                checkFileTypeMsg="只能上传 pdf、doc(x)、xls(x)、jp(e)g、png、rar 格式的文件！"
                                checkFileSizeMsg="文件大小不能超过10MB！"
                            >
                                <Button>上传文件</Button>
                            </FileUpload>
                        )}
                    </Form.Item>
                </FormLayout>
            </div>
        </div>
    );
}
